package com.hua.controller;


import com.hua.entities.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${imagepath.path}")
    private String path;

    @PostMapping("/upload")
    public R<String> uoLoad( @RequestParam("file") MultipartFile fileName /*这个名字要和前端传过来的名字一致*/) throws IOException {
        //1. 获取文件名
        String originalFilename = fileName.getOriginalFilename();
        System.out.println(path);

        File file = new File(path);
        //创建文件存储的目标文件夹
        if(!file.exists()){
            //如果目标目录不存在则创建
            file.mkdir();
        }
        //2. 获取文件的拓展名
        String nameFile = fileName.getOriginalFilename().substring(originalFilename.lastIndexOf("."));
        //3. 使用UUID生成一个全新的名字
        String s = UUID.randomUUID().toString()+nameFile;
        //把上传文件存储到目标路径上
        fileName.transferTo(new File(path,s));
        // 注意：返回的名字一定要是存储在服务器中的文件名，因为前端需要根据名字去访问图片
        return R.success(s);
    }

    @GetMapping("/download")
    public  void returnImage(String name, HttpServletResponse response )  {

        FileInputStream file = null;
        ServletOutputStream outputStream = null;
        try {
            //1. 找到目标文件
            file = new FileInputStream(new File(path+name));/*new File(path,name)也可以*/
            //通知浏览器当前输出的类型是图片
            response.setContentType("image/jpeg");
            //获取response的输出流，把图片的资源写出去
            outputStream = response.getOutputStream();

            //2. 边读边写
            byte [] bytes= new byte[1024];
            int len;
            while ((len=file.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(file!=null){
                try {
                    file.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
